<template>
  <div class="cart">
    <div class="row flex header">
      <div class="cell f1">
        <!-- <i class="iconfont icon-yduifuxuankuangxuanzhong"></i> -->
        <i
          class="iconfont"
          :class="
            isCheckAll
              ? 'icon-yduifuxuankuangxuanzhong'
              : 'icon-yduifuxuankuang'
          "
          @click="checkAll"
        ></i>
      </div>
      <div class="cell f4">礼品信息</div>
      <div class="cell f3">兑换分数</div>
      <div class="cell f2">数量</div>
      <div class="cell f2">小计</div>
      <div class="cell f1">操作</div>
    </div>
    <div class="row flex item" v-for="item in list" :key="item.id">
      <div class="cell f1">
        <i
          class="iconfont"
          @click="checkSelf(item)"
          :class="
            item.isChecked
              ? 'icon-yduifuxuankuangxuanzhong'
              : 'icon-yduifuxuankuang'
          "
        ></i>
      </div>
      <div class="cell flex f4">
        <img width="85" :src="item.coverImg | srcFormat" alt="" />
        <div>
          <p class="name">{{ item.title }}</p>
          <p>{{ item.versionDescription }}</p>
        </div>
      </div>
      <div class="cell f3">{{ item.coin }}鸡腿</div>
      <div class="cell f2 flex">
        <div class="step flex">
          <span @click="reduce(item)">-</span>
          <input type="text" v-model="item.total" />
          <span @click="add(item, $event)">+</span>
        </div>
      </div>
      <div class="cell f2">{{ item.coin * item.total }}鸡腿</div>
      <div class="cell f1">
        <input type="button" value="删除" @click="del(item)" />
      </div>
    </div>
    <div class="total">
      <div class="total-number">
        总计：<span>{{ totalCoin }}鸡腿</span>
      </div>
      <div class="submit">提交</div>
    </div>
    <Confirm ref="confirm" msg="确认要删除吗" @sure="deleteItem"></Confirm>
  </div>
</template>

<script>
import { getCartDataApi, deleteCartDataApi, addToCarApi } from "../../http/api";
import { toast } from "../../utils/toast";
import Confirm from "../common/Confirm.vue";

export default {
  components: { Confirm },
  data() {
    return {
      list: [],
      deleteId: 0,
    };
  },
  created() {
    this.getCartData();
  },
  methods: {
    async getCartData() {
      const res = await getCartDataApi();
      // console.log(res);
      this.list = res.data.map((e) => {
        e.isChecked = false;
        return e;
      });
    },
    checkAll() {
      // 利用computed 直接把每一项都取反
      const result = !this.isCheckAll;
      // 修改列表中的是否勾选
      this.list.forEach((e) => (e.isChecked = result));
    },
    checkSelf(item) {
      // 把自己的选中取反
      item.isChecked = !item.isChecked;
    },
    reduce(item) {
      if (item.total <= 1) return toast("至少购买1件", "warnning");
      item.total--;
    },
    add(item, event) {
      // 现在有个问题： 每次点击就请求一次服务器，如果用户大量点击，会给服务器造成非常大的压力
      // 我们希望，在用户松手的最后一下，才把数据同步到服务器 -- 防抖 --- 用户频繁触发一个事件，我们只让最后一次触发
      // 实现原理： 只让最后一下有效 -- 触发了事件，不是立刻做，而是等等再做，然后如果在规定时间内，再次触发，就取消上一次
      // 防抖的步骤：
      // 1. 注册事件
      // 2. 延迟执行
      // 3. 取消上次
      if (item.total >= 5) return toast("最多买5件", "warnning");
    
      item.total++;
      // 取消上次
      clearTimeout(event.target.timer);
      // 要确保每个防抖的元素都需要有自己的独立的定时器
      event.target.timer = setTimeout(() => {
        // 还要把数量同步服务器
        addToCarApi({
          productId: item.id,
          total: item.total,
          // 接口的这个参数，如果给的是1，直接使用新的total覆盖服务器的total
          modified: 1,
        }).then((res) => {
          // 自己处理失败的逻辑
        });
      }, 1000);
    },
    del(item) {
      // 确认一下要删除
      // 显示 confirm 组件
      // console.log(this.$refs);
      this.$refs.confirm.show();
      this.deleteId = item.id;
    },
    deleteItem() {
      // 通过id确定要删除谁
      // console.log(this.deleteId);
      deleteCartDataApi(this.deleteId).then((res) => {
        if (res.code === 0) {
          toast(res.message, "success");
          // 把对应的数据从数组里面删除
          const index = this.list.findIndex((e) => e.id === this.deleteId);
          this.list.splice(index, 1);
          this.deleteId = 0;
          // 偷懒的做法： 刷新 -- 一般很少这么做
          this.$refs.confirm.hide();
        } else {
          toast(res.message, "danger");
        }
      });
    },
  },
  computed: {
    isCheckAll() {
      return this.list.filter((e) => e.isChecked).length === this.list.length;
    },
    totalCoin() {
      return this.list.reduce((prev, current) => {
        // let sum = 0
        // if(current.isChecked) {
        //   sum = current.coin * current.total
        // }
        return (prev += current.isChecked ? current.coin * current.total : 0);
      }, 0);
    },
  },
};
</script>

<style lang="less" scoped>
.cart {
  .iconfont {
    color: #4488ff;
    cursor: pointer;
  }
  .f1 {
    flex: 1;
  }
  .f2 {
    flex: 2;
  }
  .f3 {
    flex: 3;
  }
  .f4 {
    flex: 4;
  }
  .cell {
    box-sizing: border-box;
  }
  .header {
    height: 60px;
    background-color: #ccc;
    text-align: center;
    line-height: 60px;
    color: #666;
  }
  .item {
    height: 100px;
    border: 1px solid #ccc;
    border-top: 0 solid #000;
    color: #333;
    font-size: 14px;
    .cell {
      line-height: 100px;
      text-align: center;
      align-items: center;
      p {
        line-height: 30px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        padding-left: 10px;
        max-width: 160px;
        &.name {
          font-weight: 700;
          font-size: 18px;
        }
      }
    }
    .step {
      span {
        box-sizing: border-box;
        border: 1px solid #ccc;
        height: 24px;
        width: 24px;
        line-height: 24px;
        text-align: center;
        cursor: pointer;
        user-select: none;
      }
      input {
        border: 1px solid #ccc;
        border-left: 0 solid #000;
        border-right: 0 solid #000;
        padding: 0;
        width: 36px;
        height: 22px;
        text-align: center;
      }
    }
  }
  .total {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    font-size: 28px;
    .total-number {
      margin: 20px;
      span {
        color: #fd604d;
      }
    }
    .submit {
      width: 200px;
      height: 60px;
      background-color: #0a328e;
      color: #fff;
      text-align: center;
      line-height: 60px;
      cursor: pointer;
    }
  }
}
</style>